import React, { useEffect, useState } from "react";
import {
  Table,
  Button,
  Input,
  Image,
  Switch,
  Space,
  Modal,
  Radio,
  message,
  Cascader,
} from "antd";
import sendFetch from "@/fetch";
import { SwitchChangeEventHandler } from "antd/es/switch";
import "@/assets/styles/Manager.scss";
import sha256 from "crypto-js/sha256";
import TextArea from "antd/es/input/TextArea";
import ReactQuill,{Quill} from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import quillEmoji from 'quill-emoji';
import "quill-emoji/dist/quill-emoji.css"; //这个不引入的话会出现emoji框一直在输入框下面的情况
//注册ToolbarEmoji，将在工具栏出现emoji；注册TextAreaEmoji，将在文本输入框处出现emoji。VideoBlot是我自定义的视频组件，后面会讲，
const { EmojiBlot, ShortNameEmoji, ToolbarEmoji, TextAreaEmoji } = quillEmoji;
Quill.register({
  'formats/emoji': EmojiBlot,
  'modules/emoji-shortname': ShortNameEmoji,
  'modules/emoji-toolbar': ToolbarEmoji,
  'modules/emoji-textarea': TextAreaEmoji,
}, true);

export default function UserList() {
  const { Column } = Table;

  interface DataType {
    key: React.Key;
    category: number;
    title: string;
    price: number;
    stock: number;
    pics: string;
    sales: number;
    description: string;
    details: string;
    is_on: boolean;
    is_recommend: boolean;
    created_at: string;
  }

  const [data, setData] = useState([]);
  const [sourceData, setSData] = useState([]);
  const [category, setCategory] = useState([]);
  const [searchTitle, setSTitle] = useState("");
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [searchOn, setSOn] = useState(false);
  const [searchRecommend, setSRecommend] = useState(false);
  const [newTitle, setNTitle] = useState("");
  const [newPrice, setNPrice] = useState(0);
  const [newStock, setNStock] = useState(0);
  const [newDescription, setNDescription] = useState("");
  const [newDetails, setNDetails] = useState("");
  const [newId, setNId] = useState(0);
  const [newCategory, setNCategory] = useState(0);
  const [isAdd, setIsAdd] = useState(true);

  const getGoodData = async () => {
    sendFetch(`/manager/getGoodInfo`).then((res: any) => {
      setData(res.data);
      setSData(res.data);
    });
  };

  useEffect(() => {
    getGoodData();
  }, []);

  const searchSourceData = () => {
    let y: DataType[] = [];
    sourceData.forEach((v: DataType) => {
      if (
        v.title.includes(searchTitle) &&
        (searchOn == undefined || v.is_on == searchOn) &&
        (searchRecommend == undefined || v.is_recommend == searchRecommend)
      )
        y.push(v);
    });
    setData(y);
  };

  const addGood = () => {
    sendFetch(`/manager/getCategoryList`).then((res) => {
      setCategory(res.data);
    });
    setIsAdd(true);
    setOpen(true);
  };

  const handleOk = () => {
    if (newTitle == "") {
      message.open({
        content: "标题不能为空！",
        type: "error",
      });
      return;
    }
    if (newPrice == 0) {
      message.open({
        content: "价格不能为0！",
        type: "error",
      });
      return;
    }
    setConfirmLoading(true);
    if (isAdd) {
      sendFetch(
        `/manager/addGood`,
        {
          title: newTitle,
          price: newPrice,
          stock: newStock,
          description: newDescription,
          details: newDetails,
          category: newCategory,
        },
        "GET"
      ).then((res: any) => {
        getGoodData();
        setConfirmLoading(false);
        setOpen(false);
      });
    } else {
      sendFetch(
        `/manager/editGood`,
        {
          id: newId,
          title: newTitle,
          price: newPrice,
          stock: newStock,
          description: newDescription,
          details: newDetails,
          category: newCategory,
        },
        "GET"
      ).then((res: any) => {
        getGoodData();
        setConfirmLoading(false);
        setOpen(false);
      });
    }
  };

  const handleCancel = () => {
    setNId(0);
    setNTitle("");
    setNPrice(0);
    setNStock(0);
    setNDescription("");
    setNDetails("");
    setNCategory(1);
    setOpen(false);
  };

  const onGood = (id: number, is_on: boolean, index: number) => {
    return () => {
      sendFetch(`/manager/onGood`, { id: id, is_on: !is_on }).then(
        (res: any) => {
          if (res.code == 3002) {
            let t: DataType[] = [...data];
            t[index].is_on = !is_on;
            setData(t);
          }
        }
      );
    };
  };

  const recommendGood = (id: number, is_recommend: boolean, index: number) => {
    return () => {
      sendFetch(`/manager/recommendGood`, {
        id: id,
        is_recommend: !is_recommend,
      }).then((res: any) => {
        if (res.code == 3003) {
          let t: DataType[] = [...data];
          t[index].is_recommend = !is_recommend;
          setData(t);
        }
      });
    };
  };

  const modules = {
    toolbar: {
      container: [
        [{ 'size': ['small', false, 'large', 'huge'] }], //字体设置
        // [{ 'header': [1, 2, 3, 4, 5, 6, false] }], //标题字号，不能设置单个字大小
        ['bold', 'italic', 'underline', 'strike'],  
        [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],
        ['link', 'image','video'], // a链接和图片的显示
        [{ 'align': [] }],
        [{
          'background': ['rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
            'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
            'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
            'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
            'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
            'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
            'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
            'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
            'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
            'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
            'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
            'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)']
        }],
        [{
          'color': ['rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
            'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
            'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
            'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
            'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
            'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
            'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
            'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
            'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
            'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
            'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
            'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)']
        }],
        ['clean'], //清空
        ['emoji'], //emoji表情，设置了才能显示
      ],
    },
    // ImageExtend: {
    //   loading: true,
    //   name: 'img',
    //   action: RES_URL + "connector?isRelativePath=true",
    //   response: res => FILE_URL + res.info.url
    // },
    'emoji-toolbar': true,  //是否展示出来
    "emoji-textarea": true, //我不需要emoji展示在文本框所以设置为false
    "emoji-shortname": true, 
  }

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          background: "#fff",
          padding: "3vh",
          margin: "3vh 0",
        }}
      >
        <div style={{ display: "flex" }}>
          <div style={{ display: "flex", alignItems: "center" }}>
            <p style={{ width: "3vw" }}>标题：</p>
            <Input
              type="text"
              value={searchTitle}
              onChange={(e) => {
                setSTitle(e.target.value);
              }}
            />
          </div>
          <div
            style={{ display: "flex", alignItems: "center", marginLeft: "3vh" }}
          >
            <Radio.Group
              defaultValue={undefined}
              style={{ marginRight: "1.5vw" }}
              buttonStyle="solid"
              value={searchOn}
              onChange={(e) => {
                setSOn(e.target.value);
              }}
            >
              <Radio.Button value={undefined}>全部</Radio.Button>
              <Radio.Button value={true}>已上架</Radio.Button>
              <Radio.Button value={false}>未上架</Radio.Button>
            </Radio.Group>
            <Radio.Group
              defaultValue={undefined}
              buttonStyle="solid"
              value={searchRecommend}
              onChange={(e) => {
                setSRecommend(e.target.value);
              }}
            >
              <Radio.Button value={undefined}>全部</Radio.Button>
              <Radio.Button value={true}>已推荐</Radio.Button>
              <Radio.Button value={false}>未推荐</Radio.Button>
            </Radio.Group>
          </div>
        </div>
        <div>
          <Button
            type="primary"
            style={{ margin: "0 1vw" }}
            onClick={searchSourceData}
          >
            搜索
          </Button>
          <Button type="primary" onClick={addGood}>
            添加商品
          </Button>
          <Modal
            title="添加商品"
            open={open}
            onOk={handleOk}
            confirmLoading={confirmLoading}
            onCancel={handleCancel}
            width={1200}
          >
            分类：
            <Cascader
              placeholder="请选择"
              style={{ width: 120 }}
              onChange={(value) => {
                setNCategory(value[value.length-1]);
              }}
              options={category}
            />
            <br />
            标题：
            <Input
              type=""
              value={newTitle}
              onChange={(e) => {
                setNTitle(e.target.value);
              }}
            />
            价格：
            <Input
              type="number"
              value={newPrice}
              onChange={(e) => {
                setNPrice(parseInt(e.target.value));
              }}
            />
            库存：
            <Input
              type="number"
              value={newStock}
              onChange={(e) => {
                setNStock(parseInt(e.target.value));
              }}
            />
            描述：
            <TextArea
              value={newDescription}
              onChange={(e) => {
                setNDescription(e.target.value);
              }}
            />
            详细：
            <ReactQuill value={newDetails} onChange={setNDetails} modules={modules}/>
          </Modal>
        </div>
      </div>
      <div>
        <Table dataSource={data}>
          <Column
            width={30}
            title="图片"
            dataIndex="pics"
            key="pics"
            render={(_, record: DataType) => (
              <>
                <Image
                  style={{
                    height: "5vh",
                    width: "5vh",
                    borderRadius: "50%",
                    overflow: "hidden",
                  }}
                  src={record.pics || "default"}
                  fallback=""
                />
              </>
            )}
          />
          <Column title="标题" dataIndex="title" key="title" />
          <Column title="价格" dataIndex="price" key="price" />
          <Column title="库存" dataIndex="stock" key="stock" />
          <Column title="销量" dataIndex="sales" key="sales" />
          <Column
            title="是否上架"
            dataIndex="is_on"
            key="is_on"
            render={(_, record: DataType, index) => (
              <>
                <Switch
                  checkedChildren="已上架"
                  unCheckedChildren="已下架"
                  checked={record.is_on}
                  onClick={onGood(record.key, record.is_on, index)}
                />
              </>
            )}
          />
          <Column
            title="是否推荐"
            dataIndex="is_recommend"
            key="is_recommend"
            render={(_, record: DataType, index) => (
              <>
                <Switch
                  checkedChildren="已推荐"
                  unCheckedChildren="未推荐"
                  checked={record.is_recommend}
                  onClick={recommendGood(
                    record.key,
                    record.is_recommend,
                    index
                  )}
                />
              </>
            )}
          />
          <Column title="创建时间" dataIndex="created_at" key="created_at" />
          <Column
            title="操作"
            key="action"
            render={(value, record: DataType) => (
              <Space size="middle">
                <button
                  className="hrefButton"
                  onClick={() => {
                    setNId(record.key);
                    setNTitle(record.title);
                    setNPrice(record.price);
                    setNStock(record.stock);
                    setNDescription(record.description);
                    setNDetails(record.details);
                    setNCategory(record.category);
                    sendFetch(`/manager/getCategoryList`).then((res: any) => {
                      // console.log(res.data)
                      setCategory(res.data);
                    });
                    setIsAdd(false);
                    setOpen(true);
                  }}
                >
                  编辑
                </button>
                <button
                  className="hrefButton"
                  onClick={() => {
                    sendFetch(
                      `/manager/deleteGood`,
                      { id: record.key },
                      "GET"
                    ).then(() => {
                      getGoodData();
                    });
                  }}
                >
                  删除
                </button>
              </Space>
            )}
          />
        </Table>
      </div>
    </div>
  );
}
